/*Author: Rony Lahav (ID:043489889)*/

import java.util.Collection;
import java.util.TreeMap;

/**
 * This class manages the FT messages by sending an FT message to all online peers
 */
public class FTManager {
	
	private static FTManager ftm;
	
	//singletone
	private FTManager(){
	}
	
	public static FTManager getInstance(){
		if (ftm==null)
			ftm=new FTManager();
		return ftm;
	}
	
	/*gets all online peers, creates an FT message and sends it to them*/
	public void sendFTToPeers(String fileName, String originPeerID) {
		if (!final_project.isShutDown()){
			String FTmsg=createFTMessage(fileName);
			SNsHandler.getInstance().propagateMessageToMyPeers(FTmsg, originPeerID);
		}
	}
	
	public void sendFTToSN(String fileName) {
		if (!final_project.isShutDown() && !final_project.inFallBackMode){
			// Get main SN
			DBTuple snTuple = final_project.getMyMainSN();
			//send an FT message
			String FTmsg="";
			if (snTuple!=null && snTuple.getStatus()){	//SN is online
				FTmsg=createFTMessage(fileName);
				sendFTToOneTuple(snTuple, FTmsg);
			}
		}
	}
	
	/**
	 * create FT message in correct format
	 * @return FT message
	 */
	private String createFTMessage(String fileName) {
		String message = MessageCenter.getInstance().createMessage_FT(Integer.toString(final_project.mainTCPSoc),fileName,Integer.toString(final_project.loadedFiles.get(fileName).length));
		return message;
	}
	
	public void sendFTToAllSNs(String fileName, String originSNKey) {
		if (!final_project.isShutDown()){
			String FTmsg=createFTMessage(fileName);
			SNsHandler.getInstance().propagateMessageToMySNs(FTmsg, originSNKey);
		}
	}
	
	protected void sendFTToOneTuple(DBTuple tuple, String FTmsg){
		// Open a dedicated thread to send FT to one specific peer
		SingleUDPMessageSender singleFT = new SingleUDPMessageSender(final_project.mainUDPSoc, tuple, FTmsg, final_project.getNewUniqueID());
		Thread thread = new Thread(singleFT);
		final_project.addThreadToLivingList(singleFT.getUniqueID(), thread);
		thread.start();
	}
}
